from waveapi import events
from waveapi import model
from waveapi import robot
from subscriber import Subscriber
import re
import logging

version_num = '0.0.0.1'
robot_name = 'Svnny'

def SubscribeUser(properties, context, url):
  logging.info(properties)
  blip_id = properties['blipId']
  blip = context.GetBlipById(blip_id)
  wave = context.GetWaveById(blip.GetWaveId())
  sub = Subscriber()

  sub.svnURL = url
  sub.waveID = wave.GetId()
  # add the subscription to the data store
  sub.put()

def UnsubscribeUser (wave_id):
  

def OnRobotAdded(properties, context):
  """Invoked when the robot has been added."""
  root_wavelet = context.GetRootWavelet()
  blip = root_wavelet.CreateBlip()
  blip.GetDocument().SetText("DEBUG: version: %s\n" % version_num)
  blip.GetDocument().AppendText("DEBUG: robot: %s\n" % robot_name)
  blip.GetDocument().AppendText("Sending subversion post-hook email messages in the google code format to %s@sbchisholm.appspotmail.com will result in them being displayed here.  \n\nTo unsubsribe from these messages simply remove Svnny from your Wave.\n" % context.GetRootWavelet().GetWaveId())

def OnBlipSubmitted(properties, context):
  blipId = properties['blipId']
  blip = context.GetBlipById(blipId)

#  if blip:
#    content = blip.GetDocument().GetText()
#    regex_pat = "!svn<(.+)>"
#    regex_mat = re.search(regex_pat, content)
#
#    if regex_mat:
#      svn_location = regex_mat.group(1)
#      blip.GetDocument().AppendText("\nsvn location: %s\n" % svn_location)
#      SubscribeUser (properties, context, svn_location)

def Notify(context):
  root_wavelet = context.GetRootWavelet()
  root_wavelet.CreateBlip().GetDocument().SetText("Hi everybody!")

if __name__ == '__main__':
  logging.getLogger().setLevel(logging.DEBUG)
  myRobot = robot.Robot('Silly-Billy', 
      image_url='http://sbchisholm.appspot.com/assets/icon.png',
      version=version_num,
      profile_url='http://sbchisholm.appspot.com/')
  myRobot.RegisterHandler(events.WAVELET_SELF_ADDED, OnRobotAdded)
  myRobot.RegisterHandler(events.BLIP_SUBMITTED,OnBlipSubmitted)
  myRobot.Run()

